package cci

import (
	"encoding/json"
	"fleetmanager/api/params"
	"fleetmanager/api/service/constants"
	"fleetmanager/client"
	"fleetmanager/client/model"
	"fleetmanager/logger"
	"fleetmanager/setting"
	"fleetmanager/workflow/components"
	"fleetmanager/workflow/directer"
	"fleetmanager/workflow/meta"
	"fmt"
	"net/http"
)

type DeleteCCINamespaceTask struct {
	components.BaseTask
}

// Execute 执行NameSpace任务
func (t *DeleteCCINamespaceTask) Execute(*directer.ExecuteContext) (output interface{}, err error) {
	defer func() { t.ExecNext(output, err) }()

	if err = t.doDelete(); err != nil {
		return nil, err
	}

	return nil, nil
}

func (t *DeleteCCINamespaceTask) doDelete() error {
	var groupId = t.Directer.GetContext().Get(directer.WfKeyScalingGroupId).ToString("")
	var requestId = t.Directer.GetContext().Get(directer.WfKeyRequestId).ToString("")

	if groupId == "" {
		// 查询底层资源是否存在NameSpace
		id, err := getNameSpace(requestId, t.getListUrl(),
			t.Directer.GetContext().Get(directer.WfKeyScalingGroupName).ToString(""))
		if err != nil {
			return err
		}

		groupId = id
	}

	if groupId == "" {
		// 没找到伸缩组, 不需要删除
		return nil
	}

	if err := t.Directer.GetContext().Set(directer.WfKeyScalingGroupId, groupId); err != nil {
		return err
	}

	url := t.getDeleteUrl()
	req := client.NewRequest(client.ServiceNameAASS, url, http.MethodDelete, nil)
	req.SetHeader(map[string]string{
		logger.RequestId: requestId,
	})
	code, rsp, err := req.DoRequest()
	if err != nil {
		return err
	}
	if code != http.StatusNoContent && code != http.StatusNotFound {
		return fmt.Errorf("delete scaling group failed, code: %d, rsp %s", code, rsp)
	}

	return nil
}

//获取请求AASS返回namespace信息的url
func (t *DeleteCCINamespaceTask) getListUrl() string {
	region := t.Directer.GetContext().Get(directer.WfKeyRegion).ToString("")
	k := setting.AASSEndpoint + "." + region
	endpoint := setting.Config.Get(k).ToString("")
	projectId := t.Directer.GetContext().Get(directer.WfKeyOriProjectId).ToString("")
	return fmt.Sprintf(endpoint+constants.ListPodGroupUrlPattern, projectId)
}

//获取请求AASS删除namespace的url
func (t *DeleteCCINamespaceTask) getDeleteUrl() string {
	region := t.Directer.GetContext().Get(directer.WfKeyRegion).ToString("")
	k := setting.AASSEndpoint + "." + region
	endpoint := setting.Config.Get(k).ToString("")
	groupId := t.Directer.GetContext().Get(directer.WfKeyScalingGroupId).ToString("")
	projectId := t.Directer.GetContext().Get(directer.WfKeyOriProjectId).ToString("")
	return fmt.Sprintf(endpoint+constants.DeletePodGroupUrlPattern, projectId, groupId)
}

//请求AASS获取namespace信息
func getNameSpace(requestId string, url string, Namespace string) (string, error) {
	req := client.NewRequest(client.ServiceNameAASS, url, http.MethodGet, nil)
	req.SetQuery(params.QueryScalingGroupName, Namespace)
	req.SetHeader(map[string]string{
		logger.RequestId: requestId,
	})
	code, rsp, err := req.DoRequest()
	if err != nil {
		return "", err
	}

	if code == http.StatusNotFound {
		// 没有找到伸缩组
		return "", nil
	}

	if code < http.StatusOK || code >= http.StatusBadRequest {
		return "", fmt.Errorf("response code %d is not the success code", code)
	}

	obj := &model.ListScalingGroupResponse{}
	if err := json.Unmarshal(rsp, obj); err != nil {
		return "", err
	}

	if obj.Count > 0 {
		return obj.InstanceScalingGroups[0].Id, nil
	}

	return "", nil
}

// NewDeleteScalingGroupTask 新建删除NameSpace任务
func NewDeleteNamespaceTask(meta meta.TaskMeta, directer directer.Directer, step int) components.Task {
	t := &DeleteCCINamespaceTask{
		components.NewBaseTask(meta, directer, step),
	}

	return t
}
